<!DOCTYPE html>
<html>
  
  <head>
    <meta charset="UTF-8">
    <title>商品列表</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" href="./css/font.css">
    <link rel="stylesheet" href="./css/xadmin.css">
    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="./lib/layui/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="./js/xadmin.js"></script>
    <!-- 引入layui.css -->
    <link
            rel="stylesheet"
            href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css"
    >
    <!-- 引入layui.js -->
    <script scr="https://www.layuicdn.com/layui-v2.5.6/layui.js"></script>

    <!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
    <!--[if lt IE 9]>
      <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
      <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  
  <body>
    <div class="x-nav">
<!--      <span class="layui-breadcrumb">-->
<!--        <a href="">首页</a>-->
<!--        <a href="">演示</a>-->
<!--        <a>-->
<!--          <cite>导航元素</cite></a>-->
<!--      </span>-->
      <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right" href="javascript:location.replace(location.href);" title="刷新">
        <i class="layui-icon" style="line-height:30px">ဂ</i></a>
    </div>
    <div class="x-body">
      <!--表单信息（搜索条件）-->
      <div class="layui-form">
        <!--这两个隐藏的输入框用来存放当前页码值，以及页面显示数据的最大行数-->
        <input type="hidden" name="pageNum" id="pageNum" value="1">
        <input type="hidden" name="pageSize" id="pageSize" value="10">
        <div class="layui-form-item">

          <div class="layui-inline">
            <label class="layui-form-label">商品关键字</label>
            <div class="layui-input-block">
              <input type="text" name="keyword" placeholder="请输入"
                     autocomplete="off" class="layui-input">
            </div>
          </div>
          <div class="layui-inline">
            <button id="getGoods" class="layui-btn" lay-submit lay-filter="searchGoods">
              <i class="layui-icon layui-icon-search"></i>
            </button>
          </div>
        </div>
      </div>
      <xblock>
<!--        <button class="layui-btn layui-btn-danger" onclick="delMany()"><i class="layui-icon"></i>批量下架</button>-->
        <button class="layui-btn" onclick="x_admin_show('添加商品','./goods-add.html',600,600)"><i class="layui-icon"></i>添加</button>
<!--        <span class="x-right" style="line-height:40px" id="goodsNum">共有商品：999 件</span>-->
      </xblock>
      <script type="text/html" id="statusTemplet">
        {{# if(d.goodsstate == 0) { }}
        <button class="layui-btn layui-btn-normal layui-btn-xs">已上架</button>
        {{# } else { }}
        <button class="layui-btn layui-btn-danger layui-btn-xs">已下架</button>
        {{# } }}
      </script>
        <script type="text/html" id="marketingstatusTmp">
            {{# if(d.newstate == 1) { }}
            <button class="layui-btn layui-btn-normal layui-btn-xs">新品</button>
            {{# } }}
            {{# if(d.hotstate == 1) { }}
            <button class="layui-btn layui-btn-normal layui-btn-xs">热卖</button>
            {{# } }}
            {{# if(d.recomstate == 1) { }}
            <button class="layui-btn layui-btn-normal layui-btn-xs">推荐</button>
            {{# } }}
        </script>

      <script type="text/html" id="table-operation">
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit">
          <i class="layui-icon layui-icon-edit"></i>编辑</a>
        {{# if(d.goodsstate == 0) { }}
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="takedown">
            <i class="layui-icon layui-icon-close"></i>下架</a>
        {{# } else { }}
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="shelves">
            <i class="layui-icon layui-icon-ok"></i>上架</a>
        {{# } }}
      </script>
<div style="text-align: center">
      <!--数据表格位置-->
      <table id="data-table" lay-filter="data-table"></table>
      <!--分页位置-->
      <div id="data-page" class="layui-table-page" lay-filter="data-page"></div>
</div>
    </div>


    <script>

      var gids=new Array()
      var gidsList=new Array()

      /*删除数组中指定下标的元素*/
      function remove(arr, item) {
        for(var i=arr.length-1;i>=0;i--)
        {
          if(arr[i]==item)
          {
            arr.splice(i,1);
          }
        }
        return arr;
      }

      /*商品-删除*/
      function user_del(obj, id) {
        // alert(id)
        layer.confirm('确认要删除吗？', function (index) {
          $.ajax({
            type: 'GET',
            url: "/users/delUserByUid",
            processData: false,
            contentType: false,
            async: false,
            success: function (res) {
              console.log(res);
            }
          });
          //发异步删除数据
          $(obj).parents("tr").remove();
          layer.msg('已删除!', {icon: 1, time: 1000});
        });
      }

      layui.use(['form','table','laypage','layer'], function() {
        var $ = layui.jquery
                ,form = layui.form,table = layui.table,laypage=layui.laypage,layer=layui.layer;
        var limits = [10, 20, 30, 40]
        // var pageNum=1
        // var pageSize=10
        var pageNum=$("#pageNum")
        var pageSize=$("#pageSize")

        let userTable=table.render({
          elem: "#data-table",
          url: "/goods/getGoodsByPageNum",//请求地址
          id:"idTest",
          parseData:function (result){
            return {
              "code":0,
              "msg":result.msg,
              "count":result.count,
              "data":result.data,
              "pageNum":result.pageNum,
              "pageSize":result.pageSize
            }
          },
          cols: [[
            // { type: 'checkbox' },
            //sort：这一列是否开启排序
            {field: "gid", width: 30, title: "ID", sort: true,hide:true},
              {field: "goods",  title: "商品",align: "center",templet: "#goodstitleimgTmp",width: 300},
            //minWidth:最小显示宽度
            {field: "goodstitle", title: "商品标题", width: 180,hide:true},
            //title:表头里的文字内容
            //field:字段名，要与后端响应的数据字段一致，否则该数据不会在表格中显示
            // {field: "goodsimg", title: "图片",width:200},
            {field: "goodsimg", title: "图片",width:120, style:"height:40px",align: "center", templet: "#imgtmp",hide:true},
            {field: "goodsprice", title: "原价（元）",width:100,hide:true},
            {field: "currentprice", title: "现价（元）",width:100,hide:true},
            {field: "price", title: "价格",width:100,align: "center", templet: "#priceTmp"},
            {field: "total", title: "库存（件）",align: "center",width:100},
            {field: "sold", title: "销量（件）",align: "center",width:100},
            {field: "newstate", hide:true},
            {field: "hotstate", hide:true},
            {field: "recomstate", hide:true},
              {field: 'marketingstatus', title: '营销状态', align: 'center', templet: '#marketingstatusTmp',width: 200},
            // {field: "goodsdesc", title: "商品详情",width:200},
            {field: "categoryList.categoryname", title: "分类",width:80,align: "center", templet:function(res){return res.categoryList[0].categoryname;}},
            {field: "goodstime", align: "center",title: "入库时间"},
            {field: 'goodsstate0', title: '商品状态', align: 'center', templet: '#statusTemplet'},
            {field: 'goodsstate', title: '商品状态', align: 'center',hide: true},
            {title: "操作",align: "center", width: 150, toolbar: "#table-operation"}
            ]],
          done:function (res, curr, count) {
            //显示总数据量
            // $('#goodsNum').html('共有数据：'+res.count +' 条')
            //显示服务器响应的数据，方便观看
            console.log("服务器返回数据")
            console.log(res)
            let data=res.data
            //  把该页所有数据的商品gid保存到gidsList用于后面的全选删除操作
            console.log(data)
            for (let i=0;i<data.length;i++){
              gidsList.push(data[i].gid)
            }
            console.log("gidsList:"+gidsList)
            laypage.render({
              elem: 'data-page',//被渲染的分页栏id，此处不需要加#号
              count: count,//数据总条数
              curr:  res.pageNum,//当前页码
              limit: res.pageSize,//当前页展示的最大行数
              limits: limits,//分页大小选项
              //分页栏的样式，具体情况可以去layui镜像网站查看
              layout:['count','prev','page','next','limit','skip'],
              jump:function (obj,first) {
                //将当前分页栏的属性打印在控制台，方便观察
                console.log("当前分页栏的属性")
                console.log(obj)
                //当操作分页栏后，获得当前页码的数据，赋值给隐藏的用来存放页码的输入框
                $("#pageNum").val(obj.curr)
                // pageNum=obj.curr
                //同理它是赋值给pageSize的
                $("#pageSize").val(obj.limit)
                if (!first){
                  $("#getGoods").click()
                  gidsList=[]
                  gids=[]
                }
              }
            });
          },
        });

        form.on('submit(searchGoods)', function (data) {
          var filed = data.field;
          console.log(data.field)
          table.reload('idTest', {
              where:filed
          });
          return false;
        });

        /*刪除一条数据*/
        table.on('tool(data-table)', function(obj){ //注：tool 是工具条事件名，data-table 是 table 原始容器的属性 lay-filter="对应的值"
          var data = obj.data; //获得当前行数据
          var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
          var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
          console.log("3333333333333333")
          console.log(data)
          var gid=data.gid;
          if(layEvent === 'detail'){ //查看
            //do somehing
          }  else if(layEvent === 'shelves'){ //上架
              //修改商品下架状态
              $.ajax({
                  type: 'GET',
                  url: "/goods/updateGoodsState/"+gid+"/"+0,
                  processData: false,
                  contentType: false,
                  async: false,
                  success: function (res) {
                      console.log(res);
                      // location.replace(location.href)
                      layer.msg('成功上架', {icon: 1});
                      userTable.reload();
                  }
              });
          }
          else if(layEvent === 'takedown'){ //下架
              //修改商品下架状态
              $.ajax({
                  type: 'GET',
                  url: "/goods/updateGoodsState/"+gid+"/"+1,
                  processData: false,
                  contentType: false,
                  async: false,
                  success: function (res) {
                      console.log(res);
                      // location.replace(location.href)
                      layer.msg('成功下架', {icon: 1});
                      userTable.reload();
                  }
              });
             }
          else if(layEvent === 'del'){ //删除
            layer.confirm('真的删除行么', function(index){
              obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
              layer.close(index);
              //向服务端发送删除指令
              $.ajax({
                type: 'GET',
                url: "/goods/"+gid+"/delGoodsByGid",
                processData: false,
                contentType: false,
                async: false,
                success: function (res) {
                  console.log(res);
                }
              });
            });
          } else if(layEvent === 'edit'){ //编辑
            //do something
            //同步更新缓存对应的值
              layer.open({
                  type: 2,
                  area: [800+'px', 600 +'px'],
                  fix: false, //不固定
                  maxmin: true,
                  shadeClose: true,
                  shade:0.4,
                  title: '编辑商品',
                  content: './goods-edit.html?newstate='+data.newstate+'&hotstate='+data.hotstate+'&recomstate='+data.recomstate,
                  success: function (layero, index) {
                      var body = layer.getChildFrame('body', index);
                      body.find("#goodstitle").val(data.goodstitle);
                      body.find("#currentprice").val(data.currentprice);
                  }
              });


          }
        });


        // var uids=new Array()
        table.on('checkbox(data-table)', function(obj){
          var data=obj.data;
          console.log("复选框")
          console.log(obj); //当前行的一些常用操作集合
          console.log(obj.checked); //当前是否选中状态

          //若是选择状态，则加入uids数组
          if (obj.checked==true){
            gids.push(data.gid)
          }else{//若为未选择状态，则删除该uid
            gids=remove(gids,data.gid)
          }
          console.log(obj.data); //选中行的相关数据
          console.log(obj.type); //如果触发的是全选，则为：all，如果触发的是单选，则为：one
          if (obj.type=="all"){
            console.log(data);
            gids=gidsList
          }
          console.log(gids)
        });

        /*用户-删除全部*/
        function delAll(argument) {
          var data = tableCheck.getData();
          layer.confirm('确认要删除吗？' + data, function (index) {
            //捉到所有被选中的，发异步进行删除
            layer.msg('删除成功', {icon: 1});
            $(".layui-form-checked").not('.header').parents('tr').remove();
          });
        }
      })


      function delMany(argument) {
        console.log("============="+gids)
        layer.confirm('确认要删除吗？' + gids, function (index) {
          //捉到所有被选中的，发异步进行删除
          layer.msg('删除成功', {icon: 1});
          $.ajax({
            type: 'GET',
            url: "/goods/"+gids+"/delManyGoods",
            processData: false,
            contentType: false,
            async: false,
            success: function (res) {
              console.log(res);
            }
          });
          // $(".layui-form-checked").not('.header').parents('tr').remove();
        });
      }
    </script>
    <script type="text/html" id="imgtmp">
      <img src="{{d.goodsimg}}" style="width:40px;height: 40px;">
    </script>
    <script type="text/html" id="goodstitleimgTmp">
        <img src="{{d.goodsimg}}" style="width:40px;height: 40px;">
        <span>{{d.goodstitle}}</span>
    </script>
    <script type="text/html" id="priceTmp">
        <span style="color: #FF5722"> {{d.currentprice}}</span>
        <span style="text-decoration: line-through"> {{d.goodsprice}}</span>
    </script>
  </body>

</html>